/*
 * @(#)org.example.register 2020/3/22/0022
 *
 * Copy Right@ 人人译视界
 */


package org.example.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/3/22/0022
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class RegisterCenterImpl implements IRegisterCenter {
	private CuratorFramework curatorFramework;
	{
		curatorFramework = CuratorFrameworkFactory.builder()
				.connectString(ZkConfig.CONNECTION_STR).sessionTimeoutMs(4000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
		curatorFramework.start();
	}
	@Override
	public void registry(String serverName, String serviceAddress) {
		String serverPath = ZkConfig.ZK_REGISTER_PATH.concat("/").concat(serverName);
		try {
			// 以服务的完整签名(包名+类名)是持久化节点
			if (curatorFramework.checkExists().forPath(serverPath) == null) {
				curatorFramework.create().creatingParentsIfNeeded()
						.withMode(CreateMode.PERSISTENT).forPath(serverPath, "0".getBytes());
			}
			String addr = serverPath.concat("/").concat(serviceAddress);
			// 具体提供服务的ip+port是上一步持久化节点下的临时节点
			String rsNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL)
					.forPath(addr, "0".getBytes());
			System.out.println("服务注册成功，" + rsNode);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
